﻿using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using ISMv1.Controls;
using Models;
using System;
using System.Linq;
using System.Windows;
using System.Windows.Input;
using ViewModels;

namespace ISMv1
{
    public partial class MainWindow : Window
    {
        public SessionViewModel Session;
        public Manager Manager { get; set; }
        public bool isSessionRunning { get; set; }
        public const string MainTitle = "ISM";
        public bool isDataDirty { get; set; }

        public MainWindow()
        {
            InitializeComponent();
            SetPage();
        }

        private void SetPage()
        {
            this.WindowState = WindowState.Maximized;
            frame_Menu.Content = new Controls.MainMenu(this);
            //frame_ButtonBar.Content = new Controls.ButtonBar(this);
            frame_ButtonBar.Visibility = Visibility.Collapsed;
            Manager = new Manager();
            Session = new SessionViewModel();
        }

        void ListViewMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            var idea = ((FrameworkElement)e.OriginalSource).DataContext as Idea;
            if (idea == null) return;
            ShowEditIdeaDialog(idea);
        }

        public void CreateNewSession()
        {
            Session = new SessionViewModel();

            var dialogSessionName = new Controls.GetSessionNameDialog();
            var isValidName = false;
            var sessionName = String.Empty;

            while (!isValidName)
            {
                dialogSessionName.ShowDialog();
                if (dialogSessionName.SessionName == null) return;
                sessionName = Manager.GetSafeFilename(dialogSessionName.SessionName);
                isValidName = Manager.ValidateSessionName(sessionName);
                if (!isValidName)
                {
                    dialogSessionName.ShowWarning();
                }
                else
                {
                    dialogSessionName.HideWarning();
                }
            }
            Manager.SetSessionPath(sessionName);
            var createdSession = Manager.CreateSessionFiles(sessionName);
            Session.Session = createdSession;
            SetSessionIsActive();

            ShowEditTriggeringQuestion();

        }

        public void ShowEditTriggeringQuestion()
        {
            if (!isSessionRunning) return;
            var triggeringquestionDialog = new TriggeringQuestionDialog(Session.Session.TriggeringQuestion);
            triggeringquestionDialog.ShowDialog();

            var trieggeringQuestion = triggeringquestionDialog.TriggeringQuestion;
            Session.Session.TriggeringQuestion = trieggeringQuestion;
        }

        private void SetSessionIsActive()
        {
            isSessionRunning = true;
            tab_Ideas.Visibility = Visibility.Visible;
            btn_CloseSession.Visibility = Visibility.Visible;
            ideaList.DataContext = Session.IdeaList;
            tabControl.SelectedItem = tab_Ideas;
        }

        private void SetSessionIsClosed()
        {
            isSessionRunning = false;
            tab_Ideas.Visibility = Visibility.Collapsed;
            btn_CloseSession.Visibility = Visibility.Collapsed;
            this.Title = MainTitle;
        }

        public void OpenSession()
        {
            //Select the session folder
            var dialog = new System.Windows.Forms.FolderBrowserDialog { SelectedPath = Manager.ProjectsDirectoryPath };
            var result = dialog.ShowDialog();

            //            var fileDialog = new Microsoft.Win32.OpenFileDialog
            //                                 {
            //                                     DefaultExt = ".ism",
            //                                     Filter = "ISM Files (*.ism)|*.ism|All Files (*.*)|*.*"
            //                                 };
            //
            //            var result = fileDialog.ShowDialog();
            if (result != System.Windows.Forms.DialogResult.OK)
                return;

            var selectedPath = dialog.SelectedPath;
            Manager.CurrentSessionPath = selectedPath;

            var newSession = Manager.ReadSession();
            if (newSession == null)
                return;

            Session.Session = newSession;


            var ideas = Manager.ReadSessionIdeas();
            if (ideas.Any())
            {
                Session.LoadIdeas(ideas);
            }

            var participants = Manager.ReadSessionParticipants();
            if (participants.Any())
            {
                Session.LoadParticipants(participants);
            }

            UpdateSessionInfo();
            SetSessionIsActive();

        }

        #region Dialogs
        private static void ShowAddUserDialog()
        {
            var dialogAddUser = new Controls.AddParticipantDialog();
            dialogAddUser.ShowDialog();
        }

        public void ShowAddIdeaDialog()
        {
            var dialogAddIdea = new Controls.EditIdeaDialog();
            dialogAddIdea.SetAddMode();
            dialogAddIdea.ShowDialog();

            if (dialogAddIdea.WasOkClicked)
            {
                var newIdea = dialogAddIdea.EditedIdea;
                Session.IdeaList.Add(newIdea);    
            }
            
            dialogAddIdea.Close();
        }

        public void ShowEditIdeaDialog(Idea idea)
        {
            var dialogEditIdea = new Controls.EditIdeaDialog(idea);
            dialogEditIdea.SetEditMode();
            dialogEditIdea.ShowDialog();

            if (dialogEditIdea.WasOkClicked)
            {
                var newIdea = dialogEditIdea.EditedIdea;
                var i = Session.IdeaList.IndexOf(idea);
                Session.IdeaList.RemoveAt(i);
                Session.IdeaList.Insert(i, newIdea);    
            }
            
            dialogEditIdea.Close();
        }

        #endregion

        #region Button Click Handlers

        private void btn_AddIdea_Click(object sender, RoutedEventArgs e)
        {
            ShowAddIdeaDialog();
        }

        private void BtnRndmIdeaClick(object sender, RoutedEventArgs e)
        {
            if(!isSessionRunning) return;
            Session.IdeaList.Add(new Idea(Session.IdeaList.Count(),0,"0","Test idea", "Test clarification"));
        }

        private void BtnNewSessionClick(object sender, RoutedEventArgs e)
        {
            CreateNewSession();
        }

        private void BtnCloseSessionClick(object sender, RoutedEventArgs e)
        {
            SaveAndCloseSession();
        }


        public void SaveAll()
        {
            if (isSessionRunning)
            {
                Manager.SaveSession(Session.Session);

                var ideaList = Session.IdeaList.ToList();
                Manager.SaveIdeaList(ideaList);

                var participantList = Session.Participants.ToList();
                Manager.SaveParticipantList(participantList);
            }
        }

        public void SaveAndCloseSession()
        {
            if (!isSessionRunning) return;
            Manager.SaveSession(Session.Session);
            
            var ideaList = Session.IdeaList.ToList();
            Manager.SaveIdeaList(ideaList);

            var participantList = Session.Participants.ToList();
            Manager.SaveParticipantList(participantList);

            SetSessionIsClosed();
        }

        public void SaveAndCloseApp()
        {
            if (isSessionRunning)
            {
                Manager.SaveSession(Session.Session);
                
                var ideaList = Session.IdeaList.ToList();
                Manager.SaveIdeaList(ideaList);

                var participantList = Session.Participants.ToList();
                Manager.SaveParticipantList(participantList);

                SetSessionIsClosed();
            }

            this.Close();
        }

        private void BtnCosaClick(object sender, RoutedEventArgs e)
        {
            var list = new List<Idea>(Session.IdeaList);

            calc1(list);
        }


        private void BtnOpenSessionClick(object sender, RoutedEventArgs e)
        {
            OpenSession();
        }

        private void BtnAddUserClick(object sender, RoutedEventArgs e)
        {
            ShowAddUserDialog();
        }

        #endregion

        #region UI

        public void UpdateSessionInfo()
        {
            this.Title = Session.Session.SessionName;
        }


        #endregion



        private void OnWindowClosing(object sender, CancelEventArgs e)
        {
            //MessageBox.Show("Closing called");

            // If data is dirty, notify user and ask for a response 
            if (isDataDirty)
            {
                var msg = "Data is dirty. Close without saving?";
                var result = MessageBox.Show(msg, "Data App", MessageBoxButton.YesNo, MessageBoxImage.Warning);
                if (result == MessageBoxResult.No)
                {
                    e.Cancel = true;
                }
                else
                {

                    SaveAndCloseApp();
                }
            }
        }


        public static void calc1(List<Idea> ideaList)
        {
            var size = ideaList.Count();
            var matriz = new int[size, size];

            //recorrer las ideas y preguntar

            for (int i = 0; i < size; i++)
            {
                for (int j = 0; j < size; j++)
                {
                    if (i == j)
                    {
                        matriz[i, j] = 1;
                    }
                    else
                    {
                        var mensaje = "Agrava significativamente";
                        var idea1 = ideaList[j].statement;
                        var idea2 = ideaList[i].statement;

                        var pregunta = String.Format("{0} - {1} - {2}", idea1, mensaje, idea2);

                        MessageBoxResult result = MessageBox.Show(pregunta, "Test", MessageBoxButton.YesNo, MessageBoxImage.Exclamation);

                        if (result == MessageBoxResult.No)
                        {
                            matriz[i, j] = 0;
                        }
                        else
                        {
                            matriz[i, j] = 1;
                        }
                    }

                }
            }


        }

        private void btn_DeleteIdea_Click(object sender, RoutedEventArgs e)
        {
            var x = ideaList.SelectedItem as Idea;
            Session.IdeaList.Remove(x);
        }

    }
}
